package v1

import (
	"bytes"
	"gin-wheel/pkg/app"
	"gin-wheel/pkg/errcode"
	"gin-wheel/pkg/util"
	"net/http"
	"path"
	"time"

	"github.com/dchest/captcha"
	"github.com/gin-gonic/gin"
)

type Captcha struct {
	Id string `json:"id"`
}

func NewCaptcha() *Captcha {
	return &Captcha{}
}

// 生成验证码ID
func (c *Captcha) GenerateId(ctx *gin.Context) {
	response := app.NewResponse(ctx)
	// 设置验证码的数字长度（个数）
	var length = 4
	captchaId := captcha.NewLen(length)
	c.Id = captchaId

	captchaMap, err := util.Struct2Map(c)
	if err != nil {
		response.ToResponse(errcode.ServerError, nil)
		return
	}
	response.ToResponse(errcode.Success, captchaMap)
}

// 获取验证码图像
func (c *Captcha) Img(ctx *gin.Context) {

	response := app.NewResponse(ctx)
	captchaId := ctx.Param("captcha_id")
	_, file := path.Split(ctx.Request.URL.Path)

	ext := path.Ext(file)
	id := file[:len(file)-len(ext)]

	if ext == "" || captchaId == "" {
		response.ToResponse(errcode.InvalidParams, nil)
		return
	}

	if ctx.Param("reload") != "" {
		captcha.Reload(id)
	}

	ctx.Header("Cache-Control", "no-cache, no-store, must-revalidate")
	ctx.Header("Pragma", "no-cache")
	ctx.Header("Expires", "0")

	var vBytes bytes.Buffer
	if ext == ".png" {
		ctx.Header("Content-Type", "image/png")
		// 设置实际业务需要的验证码图片尺寸（宽 X 高），captcha.StdWidth, captcha.StdHeight 为默认值，请自行修改为具体数字即可
		_ = captcha.WriteImage(&vBytes, id, captcha.StdWidth, captcha.StdHeight)
		http.ServeContent(ctx.Writer, ctx.Request, id+ext, time.Time{}, bytes.NewReader(vBytes.Bytes()))
	}
}

// 校验验证码
func (c *Captcha) CheckCode(ctx *gin.Context) {
	response := app.NewResponse(ctx)
	captchaId := ctx.Param("captcha_id")
	value := ctx.Param("value")
	if captchaId == "" || value == "" {
		response.ToResponse(errcode.InvalidParams, nil)
		return
	}
	if captcha.VerifyString(captchaId, value) {
		response.ToResponse(errcode.Success, nil)
	} else {
		response.ToResponse(errcode.CaptchaVerifyError, nil)
	}
	return
}
